<template>
  <div class="page">
    <!-- 展示列表模块 -->
    <div class="headerTop">
      用户名称:
      <el-input type="text" v-model="search_commodity" class="inpu" placeholder="请输入关键字"></el-input>
      用户类型:
      <el-select v-model="userSearchType" placeholder="" class="inpu">
        <el-option v-for="item in userTypes" :key="item.value" :value="item.value" :label="item.label">
        </el-option>
      </el-select>
      <el-button type="primary" size="small" @click="searchGoods">查询</el-button>
    </div>
    <div class="header_bottom">
      <el-button type="success" size="small" @click="add">添加新用户</el-button>
      <!-- <el-button type="danger" size="small" @click="deleteMany">批量删除</el-button> -->
      <el-button type="info" size="small" @click="goLog">日志记录</el-button>
      <el-button type="primary" size="small" @click="showAll" v-if="all">刷新全部</el-button>
    </div>
    <div class="container_table" id="table">
      <el-table :data="tabledata" size="mini" border id="tab" :header-cell-style="{
        'background-color': tableHead,
        color: 'white',
        fontSize: '0.3rem',
        height: '0.6rem',
        'line-height': '0.6rem',
        padding: '0.1rem'
      }" :cell-style="{ fontSize: '0.3rem' }" @row-click="getRow">
        <el-table-column label="ID" prop="id" align="center" min-width="50" fixed>
        </el-table-column>
        <el-table-column prop="user_name" label="用户名称" align="center" min-width="160">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" align="center" min-width="120">
        </el-table-column>
        <!-- <el-table-column prop="user_type" label="用户类型" align="center" min-width="100">
				</el-table-column> -->
        <!-- <el-table-column prop="childs_count" label="子账户数量" align="center" min-width="90">
				</el-table-column> -->
        <el-table-column prop="last_login_ip" label="最后登录IP" align="center" min-width="120">
        </el-table-column>
        <el-table-column prop="last_login_time" label="最后登录时间" align="center" min-width="120">
        </el-table-column>
        <el-table-column label="状态" align="center" min-width="80">
          <template slot-scope="scope">
            <span :class="scope.row.user_state == '正常' ? 'normal' : 'unnormal'" :style="{
              'background-color':
                scope.row.user_state == '冻结' ? 'orangered' : ''
            }">{{ scope.row.user_state }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" align="center">
          <template slot-scope="scope">
            <!-- <el-button type="info" size="mini" @click="showInfo(scope.row)">查看</el-button> -->
            <el-button type="primary" size="mini" @click="modifyform(scope.row)">编辑</el-button>
            <!-- <el-button type="primary"  size="mini" @click="authorize(scope.row.id)">项目授权</el-button> -->
            <!-- <el-button
              type="primary"
              v-if="userType == 2"
              size="mini"
              @click="authorize(scope.row.id)"
              >设备分配</el-button
            >
            <el-button
              type="primary"
              v-if="userType == 2"
              size="mini"
              @click="authorizeView(scope.row.id)"
              >组态分配</el-button
            >-->
            <el-button v-if="userType == 1" @click="sureDelete(scope.row.id)" type="danger" size="mini">删除</el-button>
            <el-dropdown v-if="userType == 2" placement="bottom" @command="handleCommand" trigger="click"
              style="margin-left:0.2rem;">
              <span type="primary" style="color:#409eff;cursor: pointer;">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <!-- <el-dropdown-item command="product">项目授权</el-dropdown-item> -->
                <el-dropdown-item command="equip">设备分配</el-dropdown-item>
                <el-dropdown-item command="view">组态分配</el-dropdown-item>
                <el-dropdown-item command="report">报表分配 </el-dropdown-item>
                <el-dropdown-item style="text-align:center !important;" command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination style="display:inline-block;vertical-align: middle;margin-top: 0.2rem;"
          @size-change="handleSizeChange" @current-change="current_change" :current-page="queryParams.pageNo"
          :page-size="queryParams.pageSize" :page-sizes="[10, 15, 20]" layout="total, sizes, prev, pager, next, jumper"
          :total="queryParams.total">
        </el-pagination>
      </div>
    </div>
    <!-- 报表授权 -->
    <el-dialog :visible.sync="dialogVisibleReport" :width="win.screen.width > 1280 ? '25%' : '35%'" custom-class="dlog"
      append-to-body :show-close="close" style="text-align:left;" top="120px">
      <div class="toptit">
        <span>用户分配报表</span>
        <span style="float:right;cursor: pointer;" @click="closeAuth">关闭</span>
      </div>
      <div class="topHead">
        <span style="float:left;line-height:0.5rem;color:#00BFFF;">报表树列表,点击选择</span>
        <el-button style="float:right;" type="primary" size="mini" @click="submitReport">提交</el-button>
        <!-- <el-button style="float:right;margin-right:0.2rem;" type="primary" size="mini" v-if="productExpandAll" @click="expandproductAll(false)">全部收起</el-button>
				<el-button style="float:right;margin-right:0.2rem;" type="primary" size="mini" v-else @click="expandproductAll(true)">全部展开</el-button> -->
      </div>
      <div style="text-align:left;margin-top:0.2rem;min-height:5rem;">
        <el-tree style="max-height: 500px;overflow: auto;" node-key="id" highlight-current ref="reportTree"
          class="treeBox" :check-on-click-node="true" :data="reportData" :props="reportProps" default-expand-all
          :default-checked-keys="reportDefaults" show-checkbox @check-change="reportCheckChange">
        </el-tree>
      </div>
    </el-dialog>
    <!--设备分配 -->
    <el-dialog :visible.sync="dialogVisible" :width="win.screen.width > 1280 ? '25%' : '35%'" custom-class="dlog"
      append-to-body :show-close="close" style="text-align:left;" top="120px">
      <div class="toptit">
        <span>用户分配设备</span>
        <span style="float:right;cursor: pointer;" @click="closeAuth">关闭</span>
      </div>
      <div class="topHead">
        <span style="float:left;line-height:0.5rem;color:#00BFFF;">项目设备树列表,点击选择</span>
        <el-button style="float:right;" type="primary" size="mini" @click="submitAuth">提交</el-button>
        <!-- <el-button style="float:right;margin-right:0.2rem;" type="primary" size="mini" v-if="deviceExpandAll" @click="expandDeviceAll(false)">全部收起</el-button>
				<el-button style="float:right;margin-right:0.2rem;" type="primary" size="mini" v-else @click="expandDeviceAll(true)">全部展开</el-button> -->
      </div>
      <div style="text-align:left;margin-top:0.2rem;">
        <el-tree style="max-height: 500px;overflow: auto;" node-key="id" highlight-current ref="deviceTree"
          class="treeBox" :check-on-click-node="true" :data="deviceData" :props="deviceProps" default-expand-all
          :default-checked-keys="deviceDefaults" show-checkbox @check-change="deviceCheckChange">
        </el-tree>
      </div>
    </el-dialog>
    <!--组态分配 -->
    <el-dialog :visible.sync="dialogVisibleView" :width="win.screen.width > 1280 ? '25%' : '35%'" custom-class="dlog"
      append-to-body :show-close="close" style="text-align:left;" top="120px">
      <div class="toptit">
        <span>用户分配组态</span>
        <span style="float:right;cursor: pointer;" @click="closeAuth">关闭</span>
      </div>
      <!-- <span style="line-height:0.5rem;color:#00BFFF">以下为项目组态树列表，点击方框选择</span> -->
      <div class="topHead">
        <span style="float:left;line-height:0.5rem;color:#00BFFF;">项目组态树列表,点击选择</span>
        <el-button style="float:right;" type="primary" size="mini" @click="submitAuth_2">提交</el-button>
        <!-- <el-button style="float:right;margin-right:0.2rem;" type="primary" size="mini" v-if="viewExpandAll" @click="expandViewAll(false)">全部收起</el-button>
				<el-button style="float:right;margin-right:0.2rem;" type="primary" size="mini" v-else @click="expandViewAll(true)">全部展开</el-button> -->
      </div>
      <div style="text-align: center;margin-top:0.2rem;">
        <el-tree style="max-height: 500px;overflow: auto;" node-key="id" highlight-current ref="viewTree" class="treeBox"
          :check-on-click-node="true" :data="viewData" :props="viewProps" default-expand-all
          :default-checked-keys="viewDefaults" show-checkbox @check-change="viewCheckChange">
        </el-tree>
      </div>
    </el-dialog>
    <!-- 弹出框结束 -->
  </div>
</template>

<script>
// import BMap from 'BMap'
export default {
  name: "user",
  data() {
    return {
      win: window,
      one: 1,
      zero: 0,
      all: false,
      close: false,
      stateWidth: 80,
      dialogVisible: false,
      dialogVisibleView: false,
      dialogVisibleReport: false,
      userSearchType: "",
      search_commodity: "", //输入框内容
      tableHead: localStorage.getItem("bgcolor"),
      userType: localStorage.getItem("atuser_type"),
      only: false,
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      userTypes: [
        {
          value: "",
          label: "全部"
        },
        {
          value: 2,
          label: "普通管理员"
        },
        {
          value: 3,
          label: "普通用户"
        }
      ],
      nowRow: {
        id: 0,
        user_name: ""
      },
      //pburl: 'http://39.98.232.220:8083/',
      dialogFormVisible: false,
      myproduct: [],
      tabledata: [],
      formLabelWidth2: "80px",
      formLabelWidth: "120px",
      //报表分配
      reportData: [],
      //设备授权
      deviceData: [],
      deviceChecked: [],
      deviceAllOptionId: [],
      deviceExpand: [],
      //为false可以二次操控，true不能二次操控
      deviceExpandAll: false,
      reportDefaults: [],
      deviceDefaults: [],
      reportProps: {
        id: "id",
        label: "label",
        children: "children"
      },
      deviceProps: {
        id: "id",
        label: "label",
        children: "children"
      },
      authId: 0,
      reportId: 0,
      reportAuthData: [],
      authData: [],
      //组态授权
      viewData: [],
      viewChecked: [],
      viewAllOptionId: [],
      viewExpand: [],
      //为false可以二次操控，true不能二次操控
      viewExpandAll: false,
      viewDefaults: [],
      viewProps: {
        id: "id",
        label: "label",
        children: "children"
      },
      authId_2: 0,
      authData_2: []
    };
  },

  created() {
    this.search_commodity = localStorage.getItem("userKey") || "";
    this.userSearchType = localStorage.getItem("userSearchType")
      ? Number(localStorage.getItem("userSearchType"))
      : "";
    this.queryParams.pageNo =
      Number(localStorage.getItem("currentUserNo")) || 1;
    this.showList(
      this.queryParams.pageNo,
      this.queryParams.pageSize,
      this.search_commodity,
      this.userSearchType
    );
  },

  beforeRouteLeave(to, from, next) {
    // 可以访问组件实例 `this`
    //console.log(to.name);
    if (["addUser", "userlog", "userInfo", "editUser"].indexOf(to.name) < 0) {
      localStorage.removeItem("currentUserNo");
      localStorage.removeItem("userKey");
      localStorage.removeItem("userSearchType");
    } else {
      localStorage.setItem("currentUserNo", this.queryParams.pageNo);
      localStorage.setItem("userKey", this.search_commodity);
      localStorage.setItem("userSearchType", this.userSearchType);
    }
    next();
  },

  methods: {
    current_change: function (currentPage) {
      this.queryParams.pageNo = currentPage;
      this.showList(
        currentPage,
        this.queryParams.pageSize,
        this.search_commodity,
        this.userSearchType
      );
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.showList(
        this.queryParams.pageNo,
        val,
        this.search_commodity,
        this.userSearchType
      );
    },

    //获取数据函数
    showList: function (num, size, uname, type) {
      var that = this;
      this.$http({
        method: "post",
        url: "api/user/lists",
        data: {
          keyword: uname,
          user_type: type,
          limit: size,
          page: num
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            that.tabledata = res.data.data;
            this.queryParams.total = res.data.count;
          }
        })
        .catch(error => {
          this.tabledata = [];
          this.queryParams.total = 0;
          this.queryParams.pageNo = 1;
        });
    },
    // 点击搜索输入框里的内容
    searchGoods: function () {
      this.queryParams.pageNo = 1;
      this.all = true;
      this.showList(
        1,
        this.queryParams.pageSize,
        this.search_commodity,
        this.userSearchType
      );
    },
    showAll() {
      this.all = false;
      this.queryParams.pageNo = 1;
      this.showList(1, this.queryParams.pageSize);
      this.search_commodity = "";
      this.userSearchType = "";
      //this.option=0;
    },
    add() {
      this.$router.push({
        name: "addUser",
        path: "/addUser",
        component: "addUser"
      });
    },
    goLog() {
      this.$router.push({
        name: "userlog",
        path: "/userlog",
        component: "userlog"
      });
    },

    getRow(row) {
      for (var key in this.nowRow) {
        this.nowRow[key] = row[key];
      }
      //console.log(this.nowRow);
    },

    handleCommand(command) {
      var that = this;

      //console.log(this.nowRow);
      switch (command) {
        case "report":
          setTimeout(function () {
            that.authorizeReport(that.nowRow.id);
            // that.showInfo(that.nowRow);
          }, 500);
          break;
        case "equip":
          setTimeout(function () {
            that.authorize(that.nowRow.id);
          }, 500);
          break;
        // case "product":
        //   setTimeout(function() {
        //     that.authorize(that.nowRow.id);
        //   }, 300);
        //   break;
        case "view":
          setTimeout(function () {
            that.authorizeView(that.nowRow.id);
          }, 300);
          break;
        case "delete":
          setTimeout(function () {
            that.sureDelete(that.nowRow);
          }, 300);
          break;
      }
    },

    showInfo(row) {
      this.$router.push({
        name: "userInfo",
        path: "/userInfo",
        component: "userInfo"
      });
      localStorage.setItem("userInfoId", row.id);
    },

    modifyform(row) {
      this.$router.push({
        name: "editUser",
        path: "/editUser"
      });
      localStorage.setItem("editUserId", row.id);
    },
    // 报表分配
    authorizeReport(id) {
      var that = this;
      that.reportId = id;
      this.reportDefaults = [];
      this.dialogVisibleReport = true;

      this.$http({
        method: "post",
        url: "api/user/authStatementsTree",
        data: {
          user_id: id
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            this.reportData = res.data.data;
            var defaults = [];
            for (let i = 0, len = this.reportData.length; i < len; i++) {
              //加后缀是避免项目id和报表id相同
              this.reportData[i].id=this.reportData[i].id+"report";
              for (
                let n = 0, len2 = this.reportData[i].children.length;
                n < len2;
                n++
              ) {
                if (this.reportData[i].children[n].auth) {
                  defaults.push(that.reportData[i].children[n].id);
                }
              }
            }
            //this.deviceExpand=this.deviceAllOptionId;
            this.reportDefaults = defaults;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    authorize(id) {
      var that = this;
      this.authId = id;
      //this.deviceAllOptionId=[];
      this.deviceDefaults = [];
      this.dialogVisible = true;
      this.$http({
        method: "post",
        url: "api/user/authEquipsTree",
        data: {
          id: id
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            this.deviceData = res.data.data;
            var defaults = [];
            for (let i = 0, len = this.deviceData.length; i < len; i++) {
              //this.deviceAllOptionId.push(that.deviceData[i].id);
              //加后缀是避免项目id和设备id相同
              this.deviceData[i].id=this.deviceData[i].id+"equip";
              for (
                let n = 0, len2 = this.deviceData[i].children.length;
                n < len2;
                n++
              ) {
                if (this.deviceData[i].children[n].auth) {
                  defaults.push(that.deviceData[i].children[n].id);
                }
              }
            }
            //this.deviceExpand=this.deviceAllOptionId;
            this.deviceDefaults = defaults;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    deviceCheckChange(data, checked, indeterminate) {
      this.authData = this.$refs.deviceTree.getCheckedKeys(true); //只要叶子节点（即设备id）
    },
    reportCheckChange(data, checked, indeterminate) {
      this.reportAuthData = this.$refs.reportTree.getCheckedKeys(true); //只要叶子节点（即设备id）
    },
    // 提交报表分配
    submitReport() {
      var that = this;
      this.$http({
        method: "post",
        url: "api/user/setAuthStatements",
        data: {
          user_id: this.reportId,
          statement_id: this.reportAuthData
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            this.$message({
              message: "恭喜，授权报表成功!",
              type: "success",
              center: true
            });
            this.dialogVisibleReport = false;
            this.showList(
              this.queryParams.pageNo,
              this.queryParams.pageSize,
              this.search_commodity,
              this.fId
            );
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    submitAuth() {
      var that = this;
      this.$http({
        method: "post",
        url: "api/user/setAuthEquips",
        data: {
          id: this.authId,
          equip_id: this.authData
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            this.$message({
              message: "恭喜，授权用户成功!",
              type: "success",
              center: true
            });
            this.dialogVisible = false;
            this.showList(
              this.queryParams.pageNo,
              this.queryParams.pageSize,
              this.search_commodity,
              this.userSearchType
            );
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    closeAuth() {
      this.dialogVisible = false;
      this.dialogVisibleView = false;
      this.dialogVisibleReport = false;
    },

    authorizeView(id) {
      var that = this;
      this.authId_2 = id;
      //this.viewAllOptionId=[];
      this.viewDefaults = [];
      this.dialogVisibleView = true;
      this.$http({
        method: "post",
        url: "api/user/authViewsTree",
        data: {
          id: id
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            this.viewData = res.data.data;
            var defaults = [];
            for (let i = 0, len = this.viewData.length; i < len; i++) {
              //this.viewAllOptionId.push(that.viewData[i].id);
              //加后缀是避免项目id和组态id相同
              this.viewData[i].id=this.viewData[i].id+"view";
              for (
                let n = 0, len2 = this.viewData[i].children.length;
                n < len2;
                n++
              ) {
                if (this.viewData[i].children[n].auth) {
                  defaults.push(that.viewData[i].children[n].id);
                }
              }
            }
            //this.viewExpand=this.viewAllOptionId;
            this.viewDefaults = defaults;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    viewCheckChange(data, checked, indeterminate) {
      this.authData_2 = this.$refs.viewTree.getCheckedKeys(true);
    },

    submitAuth_2() {
      var that = this;
      this.$http({
        method: "post",
        url: "api/user/setAuthViews",
        data: {
          id: that.authId_2,
          view_id: that.authData_2
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            this.$message({
              message: "恭喜，授权用户成功!",
              type: "success",
              center: true
            });
            this.dialogVisibleView = false;
            this.showList(
              this.queryParams.pageNo,
              this.queryParams.pageSize,
              this.search_commodity,
              this.userSearchType
            );
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    changeState(row, value) {
      var that = this;
      this.$http({
        method: "post",
        url: "api/user/setState",
        data: {
          state: value,
          id: row.id
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            this.$message({
              message: "恭喜,修改用户状态成功!",
              type: "success",
              center: true
            });
          }
        })
        .catch(error => {
          console.log(error);
          this.showList(
            this.queryParams.pageNo,
            this.queryParams.pageSize,
            this.search_commodity,
            this.userSearchType
          );
        });
    },

    sureDelete(id) {
      this.$confirm(
        "删除后无法恢复,该用户将无法登录,用户相关信息也将清除,是否确认删除?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.handleClick(id);
        })
        .catch(() => {
          // this.$message({
          //     type: 'info',
          //     message: '已取消删除'
          // });
        });
    },

    handleClick(id) {
      var that = this;
      this.$http({
        method: "post",
        url: "api/user/delete",
        data: {
          id: id
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            that.showList(
              this.queryParams.pageNo,
              this.queryParams.pageSize,
              this.search_commodity,
              this.userSearchType
            );
          }
        })
        .catch(error => {
          console.log(error);
        });
      //console.log(tab, event);
    }
  }
};
</script>

<style scoped>
.inpu,
.sele {
  margin-right: 0.4rem;
}

.container_table {
  width: 99.4%;
}

.inpu {
  width: 5rem;
}

.normal,
.unnormal {
  display: inline-block;
  width: 1.2rem;
  height: inherit;
  color: #fff;
  vertical-align: middle;
}

.normal {
  background-color: forestgreen;
}

.unnormal {
  background-color: #aaa;
}

.dlog {
  box-sizing: border-box;
  padding: 0 !important;
  position: relative;
}

.topHead {
  width: 100%;
  height: 0.8rem;
  line-height: 0.8rem;
  border-bottom: 1px solid #ccc;
}

.treeBox /deep/ .el-tree-node__label {
  font-size: 14px !important;
  font-weight: 700 !important;
  color: #111;
}

.treeBox /deep/ .el-tree-node__children .el-tree-node__label {
  font-size: 14px !important;
  font-weight: normal !important;
  color: #333;
}

/* .transferBox {
		text-align: left;
		display: inline-block;
		overflow: auto;
		padding-bottom: 0.2rem;
	}

	.transferBox /deep/ .el-transfer-panel {
		width: 300px;
		padding-bottom: 0.8rem;
	}

	.transferBox /deep/ .el-transfer-panel:first-child {
		padding-bottom: 0;
	} */
</style>
